# 求列表中那个数之和等于目标变量
def two_sum(nums, target):
    res = []
    nums.sort()
    low, high = 0, len(nums) - 1
    while low < high:
        left, right = nums[low], nums[high]
        tmp = left + right
        if tmp > target:
            while high > low and nums[high] == right:
                high -= 1
        elif tmp < target:
            while low < high and nums[low] == left:
                low += 1
        else:
            res.append([left, right])
            while high > low and nums[high] == right:
                high -= 1
            while low < high and nums[low] == left:
                low += 1
    return res


def three_sum(nums, target):
    def two_sum(nums, target, start):
        res = []
        low, high = start, len(nums) - 1
        while low < high:
            left, right = nums[low], nums[high]
            tmp = left + right
            if tmp > target:
                while high > low and nums[high] == right:
                    high -= 1
            elif tmp < target:
                while low < high and nums[low] == left:
                    low += 1
            else:
                res.append([left, right])
                while high > low and nums[high] == right:
                    high -= 1
                while low < high and nums[low] == left:
                    low += 1
        return res
    nums.sort()
    i = 0
    res = []
    while i < len(nums):
        # print(i)
        tmp = two_sum(nums, target - nums[i], i + 1)
        for item in tmp:
            item.append(nums[i])
            res.append(list(item))
        while i < len(nums) - 1 and nums[i] == nums[i + 1]:
            i += 1
        i += 1
    return res


def nSum(self, nums, n, target):
    """注意，此函数的nums应是排序后的数组，否则每层递归都要对nums排序，效率极低"""
    if len(nums) < n:
        return []
    res = []

    if n == 2:
        left, right = 0, len(nums) - 1
        while left < right:
            if nums[left] + nums[right] == target:
                res.append([nums[left], nums[right]])
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1
                left += 1
                right -= 1
            elif nums[left] + nums[right] > target:
                right -= 1
            else:
                left += 1
        return res
    else:
        for first_idx in range(len(nums)):
            if first_idx > 0 and nums[first_idx] == nums[first_idx - 1]:
                continue
            subres = self.nSum(nums[first_idx + 1:], n - 1, target - nums[first_idx])
            for i in range(len(subres)):
                res.append([nums[first_idx]] + subres[i])
        return res


if __name__ == '__main__':
    # print(two_sum([1,1,1,2,2,3,3], 4))
    print(three_sum([1,1,2,1,3,4,5,7,4,9,5,3,2], 12))